<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/5
 * Time: 下午4:51
 */

namespace App\Http\Controllers\Api;


use App\Models\UserSign;
use App\Models\UserSubscribe;
use App\Utils\ArrayUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;


class SubscribeController extends AuthorizedController
{
    public function create(Request $request)
    {
        $rules = [
            'template_id' => 'required|string',
            'type' => 'required|integer',
            'status' => 'required|integer|in:0,1',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->success();
        }

        $user = $request->apiUser;

        $userSubscribe = UserSubscribe::create([
            'user_id' => $user->id,
            'template_id' => $request->template_id,
            'date' => date('Y-m-d'),
            'type' => $request->type,
            'status' => 0
        ]);


        return $this->success([
            'user_subscribe' => ArrayUtil::getFields($userSubscribe, ['id', 'date', 'type', 'status'])
        ]);
    }

    public function change(Request $request)
    {
        $rules = [
            'user_subscribe_id' => 'required|string',
            'status' => 'required|integer|in:1,2',
            //'is_allow' => 'required|integer|in:0,1',
        ];

        $isAllow = $request->get('is_allow', 0);

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->success();
        }

        $user = $request->apiUser;

        /** @var UserSubscribe $userSubscribe */
        $userSubscribe = UserSubscribe::where([
            'user_id' => $user->id,
            'id' => $request->user_subscribe_id
        ])->first();
        if (!empty($userSubscribe)){
            $userSubscribe->status = $request->status;
            $userSubscribe->is_allow = $isAllow;
            $userSubscribe->save();

            if ($userSubscribe->status == 2 && $user->auth_subscribe == 0){
                //订阅成功，并且没有修改过订阅状态的情况下，修改订阅状态
                $user->auth_subscribe = 1;
                $user->save();
            }

            return $this->success([
                'user_subscribe' => ArrayUtil::getFields($userSubscribe, ['id', 'date', 'type', 'status'])
            ]);
        }

        return $this->error('订阅记录不存在');


    }


}
